<template>
	<!-- lzy 2023年4月20日 16点31分 -->
    <!-- 客服页面 -->
	<div id="customer_box">
		<!-- <div id="div1" @click="saveFriend()">
		</div>
		<el-input v-model="inceptId" style="width: 50px;" placeholder="请输入连接人id"></el-input> -->
        <div style="width: 900px; height: 400px;margin: 0 auto;">
            <div>
                <el-select @change="updateCustomerStatus" v-model="customerStatus" placeholder="请选择">
                    <el-option
                    v-for="item in status"
                    :key="item.value"
                    :label="item.value"
                    :value="item.id">
                    </el-option>
                </el-select>
            </div>
            <div class="friendList">
				<div class="friend" @click="openFriend(item,index)" tabindex="1" v-for="item,index in inceptList" :key="item.id">
					<el-avatar style="float:left;margin: 2px 0 0 2px;" :src="item.avatarUrl"></el-avatar>
					<p class="friend_nickname">{{item.nickName}}</p>
					<el-badge :hidden="item.unread == 0" :max="99" :value="item.unread" class="unread_msg_badge"></el-badge>
				</div>
            </div>
			<!-- <div id="customerWindow_shade" v-if="customerWindowShade"></div> -->
            <!-- <div id="customerWindow" v-if="!customerWindowShade"> -->
            <div id="customerWindow">
                <div class="customer_window_main">
                    <div class="wxchatBorderRightMid">
                        <div class="wxchatBorderRightMid_header">
							<p style="margin-left: 20px;">{{inceptForm.nickName}}</p>
                        </div>
                        <div style="margin-top: 15px;">
                        <el-row>
                            <el-col v-for="item in inceptIds" :key="item.id" >
                                <div v-show="item == inceptId" class="chatPop1" :id="'chatPop' + item" style=" overflow-y:auto; height:350px;width:100%">
                                    <div>
                                        <!-- 聊天记录item -->
                                        <div class="chat-item" v-for="(item) in msg" :key="item.id" :id="'msg' + item.id">
                                            <!-- 时间  -->
                                            <div class="time" v-if="item.is_withdrawn === 0">{{item.send_time}}</div>
                                            <!--a - 自己的信息-->
                                            <div class="content-wrapper-right" v-if="item.inceptId == inceptId & inceptId != 0">
                                                <!-- 头像 -->
                                                <img class="avator-avator-right" :src="'http://101.43.223.224:8765/image/getImageById?id=' + userForm.avatarId" style="width:40px;height:40px;margin-top:5px"/>
                                                <div style="width: 284px;float: right;">
                                                    <!-- text - 文字 -->
                                                    <div class="chat-content-right">{{item.content}}</div>
                                                </div>
                                            </div>
                                            <!-- b - 对方的消息  -->
                                            <div class="content-wrapper-left" v-if="item.serderId == inceptId">
                                                <!-- 头像 -->
                                                <img class="avator-avator-left" :src="inceptForm.avatarUrl" style="width:40px;height:40px;margin-top:5px"/>
                                                <div style="width: 284px;float: left;">
                                                    <!-- text - 文字 -->
                                                    <div class="chat-content-left">{{item.content}}</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                        </div>
                    </div>
                    <!-- 操控台 -->
                    <div v-show="operatingFloor">
                        <el-input
                            type="textarea"
                            :rows="2"
                            placeholder="请输入内容"
							@keyup.enter.native="sendMsg"
                            v-model="content">
                        </el-input>
                        <el-button @click="sendMsg">发送</el-button>
                    </div>
                </div>
            </div>
        </div>
	</div>
</template>
<script>
export default {
	name: "CustomerHome",
	data() {
		return {
			// websocket连接路径前缀	
			// wsBaseURL: 'ws://127.0.0.1:8088',
			wsBaseURL: 'ws://101.43.223.224:16981',
            // 操作台状态
            operatingFloor: false,
            // 客服状态
            customerStatus: 1,
            // 客服状态列表
            status: [
                {
                    id: 1,
                    value: "在线"
                },
                {
                    id: 2,
                    value: "离线"
                }
            ],
			// 用户ids 
			inceptIds: [],
            // 用户信息列表
            inceptList: [],
			// 用户id
			userId: 0,
			// 客服按钮
			customerBtn: true,
			ws: null,
			// 消息接收人
			inceptId: 0,
			// 消息
			content: '',
			// 消息记录
			msg: [],
			// 当前登录的用户信息
			userForm: {},
			// 接收人对象
			inceptForm: {},
			// 聊天内容
			lt: {
				"inceptId":"",
				"content":"",
				"senderId":"",
			},
			// 连接角色 0普通用户 1客服
			role: 1,
			// 消息信息列表
			msgMap: new Map(),
			// 聊天内容遮罩
			customerWindowShade: true,
		}
	},
	created () {
		this.userId = JSON.parse(window.localStorage.getItem('userInfo')).id
		console.log(this.userId+"111")
	},
	watch: {
	},
	mounted () {
		// 根据用户id获取用户信息
		this.getUserById()
        // 默认建立连接
        this.saveFriend()
	},
	methods: {
		// 将滚动条在底部
		updateScroll(inceptId){
			const that = this
			this.$nextTick(() => {
				if (inceptId != 0) {
					var idName = "chatPop" + inceptId
					var element = document.getElementById(idName);
					element.scrollTop = element.scrollHeight;
				}
			})
		},
        // 打开好友
        openFriend(item,index){
			this.inceptList[index].unread = 0
			this.inceptForm = item
            // 展示操控台
            this.operatingFloor = true
			// 切换聊天窗口
			this.inceptId = item.id
			// 隐藏聊天内容遮罩
			this.customerWindowShade = false
			// 滚动条实时更新到底部
			this.updateScroll(this.inceptId)
        },
        // 更改客服状态
        updateCustomerStatus(item){
            if (item == 1) {
                // 建立连接
                this.saveFriend()
            } else {
                this.ws.close()
            }
        },
		// 获取发信息的用户信息
		getUserById(){
			this.$axios.get('/sysUser/getUserById', {
                params: {
                    id: this.userId
                }
            }).then(res => {
				if (res.data.flag) {
					this.userForm = res.data.data
				} else {
                    
				}
			})
		},
		// 发送消息
		sendMsg () {
			if (this.content.trim() !== '') {
				// 消息接收人
				this.lt.inceptId = this.inceptId
				// 发送信息内容
				this.lt.content = this.content
				// 发送人
				this.lt.senderId = this.userId
				// 发送消息
				this.ws.send(JSON.stringify(this.lt))
				var obj = {}
				// 发送内容
				obj.content = this.content
				// 接收人id
				obj.serderId = this.userId
				// 消息接收人id
				obj.inceptId = this.inceptId
				this.msg.push(obj)
				// chushihua 
				this.content = ''
				// 滚动条实时更新到底部
				this.updateScroll(this.inceptId)
			} else {
				this.message("不能发送空消息", "warning")
				// 清除文本框空格
				this.content = this.content.trim()
			}
		},
		// 新增会话
		saveFriend () {
			const that = this
			if (this.userId == null || this.userId == 'null' && this.ws == null) {
				this.$router.push({path: "/Login"})
			} else {
				// 显示客服窗口
				this.ws = new WebSocket(that.wsBaseURL + "/customerWebSocket/" + this.userId + "/" + this.role)
				this.ws.onopen = function (event) {
                    console.log(event)
				}

				//接收到消息的回调方法
				this.ws.onmessage = function (msg) {
					var data = JSON.parse(msg.data)
                    let flag = true
					console.log(that.inceptIds)
					debugger
                    // 检查该用户是否已经建立会话
                    that.inceptIds.forEach(item => {
                        if (item == data.sender) {
                            flag = false
                        }
                    })
                    // 未建立会话添加
                    if (flag) {
                        that.inceptIds.push(data.sender)
						that.getInceptById(data.sender)
                    } else {
                        
                    }
					// 判断当前是否在停留在消息发送人的会话窗口
					if (data.sender != that.inceptId) {
						that.inceptList.forEach(item => {
							if (item.id == data.sender) {
								item['unread'] += 1;
							}
						})
					}
					if (data.context.trim() !== '') {
						var obj = {}
						// 对方发的消息
						obj.content = data.context
						// 发送人的id
						obj.serderId = data.sender
						// 消息接收人id
						obj.inceptId = data.inceptId
						that.msg.push(obj)
						// 滚动条实时更新到底部
						that.updateScroll(data.sender)
					}
				}

				//连接关闭的回调方法
				this.ws.onclose = function () {
					// 关闭连接时保存用户聊天记录
					// that.saveChatRecord()
				}
			}
		},
		// 保存用户聊天记录
		saveChatRecord () {
			this.$axios.post("/customer/saveChatRecord", {
				msg: JSON.stringify(this.msg),
				userId: JSON.stringify(this.userId)
			}).then(res => {
				
			})
		},
		// 获取消息接收人详细信息
		getInceptById(inceptId){
			this.$axios.get("/upUser/getUserById", {
                params: {
                    id: inceptId
                }
            }).then(res => {
				if (res.data.flag) {
					var inceptForm = res.data.data
					// 初始化用户的未读消息
					inceptForm.unread = 0
					this.inceptList.push(inceptForm)
				} else {

				}
			})
		},
		// 消息提示框
		message (message, type) {
			this.$message({
				message: message,
				type: type
			})
		}
	}
}
</script>

<style scoped>
*{
	margin: 0;
	padding: 0;
}
#customer_box{
	width: 100%;
	height: 100%;
	position: relative;
}
/* #div1{
	width: 50px;
	height: 50px;
	background: #FFF200;
	border-radius: 50%;
	background-image: url('../../assets/image/customer.png');
	background-position: center;
	background-repeat: no-repeat;
	background-size: 60%;
	cursor:pointer;
}
#div1:hover{
	background-image: url('../../assets/image/customer1.png');
	background-position: center;
	background-repeat: no-repeat;
	background-size: 60%;
	cursor:pointer;
} */
#customerWindow{
	width: 700px;
	height: 500px;
	background-color: white;
	box-shadow:4px 4px 15px rgb(144, 144, 144);
    float: left;
}
.customer_window_header{
	width: 100%;
	height: 60px;
	background-color: #FFF200;
}
.el-icon-close{
	cursor: pointer;
	position: absolute;
	right: 10px;
	top: 10px;
}
.wxchatBorderRightMid {
	width: 100%;
	height: 100%;
	background-color: #f5f5f5;
	display: block;
	float: left;
}
/* 聊天样式 */
.chatPop1 span {
	background-color: #fff;
	padding: 5px 8px;
	display: inline-block;
	border-radius: 10px;
	margin: 0px 0 10px 10px;
	position: relative;
	border: 1px solid #E3E3E3;
	max-width: 290px;
}

.chatPop1 span::after {
	content: '';
	border: 8px solid #ffffff00;
	border-right: 8px solid #fff;
	position: absolute;
	top: 8px;
	left: -16px;
}
/* 消息样式 */
.chat-item{
	font-size: 15px;
	color: #000000;
}
.time{
	width: 100%;
	height: 18px;
	color: #000000;
	margin-left: auto;
	margin-right: auto;
	text-align: center;
	font-size: 13px;
	margin-top: 10px;
	z-index: 2;
}
.content-wrapper-right{
	display: flow-root;
	padding: 10px 10px 0 10px;
}
.avator-avator-right{
	width: 50px;
	height: 50px;
	border-radius: 50%;
	border: #fff solid 1px;
	float: right;
}
.chat-content-right{
	float: right;
	background-color: #95ec69;
	margin-right: 6px;
	padding: 4px 10px;
	border-radius: 6px;
	margin-top: 8px;
	line-height: 28px;
}
.content-wrapper-left{
	display: flow-root;
	padding: 10px 10px 0 10px;
}
.avator-avator-left{
	width: 50px;
	height: 50px;
	border-radius: 50%;
	border: #fff solid 1px;
	float: left;
}
.chat-content-left{
	float: left;
	background-color: #fff;
	margin-left: 6px;
	padding: 4px 10px;
	border-radius: 6px;
	margin-top: 8px;
	line-height: 28px;
}
.friendList{
    width: 150px;
    height: 500px;
    float:left;
    background-color: #F5F5F5;
    overflow: hidden;
    overflow: scroll;
}
.friend{
    height: 45px;
    width: 100%;
    line-height: 45px;
    cursor: pointer;
	position: relative;
}
.unread_msg_badge {
	position: absolute;
	top: 5px;
	right: 4px;
}
.friend:hover{
    background-color: #D8D7D7;
}
.friend:focus{
    background-color: #C8C6C5;
}
.friend_nickname{
    font-size: 12px;
    width: 50px;
    float: left;
    margin: 0px;
    margin-left: 10px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
.wxchatBorderRightMid_header{
    width: 100%;
    height: 50px;
    background-color: #FFF200;
	line-height: 50px;
}
#customerWindow_shade{
	width: 700px;
	height: 500px;
	background-color:#000000;
	box-shadow:4px 4px 15px rgb(144, 144, 144);
    float: left;
}
</style>